<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        img {
            width: 200px;
            height: 300px;
        }
    </style>
</head>

<body>

    <script>
        let arr = ["1.jpg",
                "2.png",
                "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Ftupian.qqjay.com%2Fu%2F2017%2F0920%2F3_152937_8.jpg&refer=http%3A%2F%2Ftupian.qqjay.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1637318999&t=c598ecfb9abc60f8518e8e077982569d"
            ]
            // window.addEventListener('load', function() {
            // ** 创建一个函数 `preloadImages(sources, callback)`，
            // 来加载来自数组 `source`
            // 的所有图片， 并在准备就绪时运行 `callback`。 **
        function loaded() {
            alert("Images loaded")
        }

        function preloadImages(sources, callback) {
            let count = 0;
            for (var i = 0; i < sources.length; i++) {
                let img = document.createElement('img');
                img.src = sources[i];
                img.onload = function() {
                    count++;
                    document.body.append(img)
                    console.log(count);
                    if (count == sources.length) {
                        callback()

                    }
                }
                img.onerror = function() {
                    count++;
                    console.log(count);
                    document.body.append(img)
                        // alert("Error occurred while loading image");
                }
            }
        }
        preloadImages(arr, loaded);
    </script>
</body>

</html>